package chances.webui.taglibs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

@SuppressWarnings("serial")
public class SelectTag extends InputTag {

	private String linkId;

	private String linkUrl;
	private String selectClass;
	private List<String> excludeList;

	@Override
	protected void initContext(Map<String, Object> context) {
		context.put("select", this.input);
	}

	@Override
	protected void reset() {

		super.reset();
		this.setType("select");
		this.linkId = null;
		this.linkUrl = null;
		selectClass = null;
	}

	@SuppressWarnings("rawtypes")
	public boolean selected(Object obj) {
		Object aValue = this.input.getValue();
		if (aValue.equals(obj)) {
			return true;
		}
		if (aValue.getClass().isArray()) {
			Object[] arr = (Object[]) aValue;
			int idx = Arrays.binarySearch(arr, obj);
			return idx > -1;

		} else if (String.class.isInstance(aValue)) {
			String[] ids = aValue.toString().split(",");
			int idx = Arrays.binarySearch(ids, obj);
			return idx > -1;
		} else if (Collection.class.isInstance(aValue)) {
			return ((Collection) aValue).contains(obj);
		}
		return false;
	}

	public String getLinkId() {
		return linkId;
	}

	public void setLinkId(String linkId) {
		this.linkId = linkId;
	}

	public String getLinkUrl() {
		return linkUrl;
	}

	public void setLinkUrl(String linkUrl) {
		this.linkUrl = linkUrl;
	}

	public String getSelectClass() {
		return selectClass;
	}

	public void setSelectClass(String selectClass) {
		this.selectClass = selectClass;
	}

	public List<String> getExcludeList() {
		return excludeList;
	}

	public void setExclude(String exclude) {
		this.excludeList =  new ArrayList<String>();
		String [] splits = exclude.split(",");
		for (String split : splits) {
			if(StringUtils.isNotBlank(split))
				this.excludeList.add(split);
		} 
	}
}
